//
//  DetailViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/5.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/SDWebImageDownloader.h>
#import <FLAnimatedImage/FLAnimatedImage.h>
#import <Masonry/Masonry.h>
#import <SVProgressHUD/SVProgressHUD.h>
@import AVFoundation;
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "DetailTableViewCell.h"
#import "LoginViewController.h"
#import "CommentView.h"
#import "DetailGroupHeaderView.h"
#import "ShareManager.h"
#import "NetManager.h"
#import "User.h"
typedef NS_ENUM(NSInteger, COLLECTTYPE) {
    COLLECTTYPE_YES = 1,
    COLLECTTYPE_NO = 0
};
@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate, AVSpeechSynthesizerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIBarButtonItem *collectItem;
@property (nonatomic, strong) CommentView *commentView;

@property (nonatomic, strong) NSArray *steps;
@property (nonatomic, strong) NSArray *burdens;
@property (nonatomic, strong) NSArray *commentList;
@property (nonatomic, copy) NSString *img_stepsURL;
@property (nonatomic, strong) UIButton *speechButton;
@property (nonatomic, strong) AVSpeechSynthesizer *synth;
@end

@implementation DetailViewController
static BOOL isCollect = NO;
#pragma mark - lifeCycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self fetchCommentList];
    UIBarButtonItem *collectItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"food_notCollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(collectThisFood)];
    self.collectItem = collectItem;
    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"food_share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(shareThisFood)];
    self.navigationItem.rightBarButtonItems = @[shareItem, collectItem];
    
    isCollect = [[self.foodInfo safeObjectForKey:@"isCollect"] boolValue];
    if (isCollect) {
        [self.collectItem setImage:[[UIImage imageNamed:@"food_collect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }else {
        [self.collectItem setImage:[[UIImage imageNamed:@"food_notCollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    }
    
    __weak typeof(self) ws = self;
    CGFloat btnWidth = 44;
    [self.speechButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(ws.view.mas_right).offset(-10);
        make.bottom.equalTo(ws.commentView.mas_top).offset(10);
        make.size.mas_equalTo(CGSizeMake(btnWidth, btnWidth));
    }];
    [self.commentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(ws.view.mas_bottom);
        make.left.right.equalTo(ws.view);
        make.height.equalTo(@44);
    }];
    _commentView.textViewDidChange = ^(CGSize textSize) {
        [ws updateCommentViewFrameByCommentTextSize:textSize object:ws];
    };
    
    [self interactiveWithType:INTERACTIVETYPE_SCAN];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.commentList.count != 0) {
        return 4;
    }else {
        return 3;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.commentList.count != 0) {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            return self.burdens.count;
        } else if (section == 2) {
            return self.steps.count;
        } else {
            return self.commentList.count;
        }
    } else {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            return self.burdens.count;
        } else {
            return self.steps.count;
        }
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailTableViewCell *cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"foodDescriptionCell" forIndexPath:indexPath];
        cell.nameLabel.text = [self.foodInfo safeObjectForKey:@"title"];
        cell.tagsLabel.text = [self.foodInfo safeObjectForKey:@"tags"];
        cell.imtroLabel.text = [self.foodInfo safeObjectForKey:@"imtro"];
        
        FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.img_stepsURL]]];
        NSURL *iconImgURL = [NSURL URLWithString:[[self.steps safeObjectAtIndex:indexPath.row] safeObjectForKey:@"img"]];
        [cell.animatedImgView sd_setImageWithURL:iconImgURL];
        cell.iconImgUrl = iconImgURL;
        if (image) {
            cell.controlAnimateBtn.hidden = NO;
        }else {
            cell.controlAnimateBtn.hidden = YES;
        }
        cell.animatedImage = image;
        cell.animatedImgView.userInteractionEnabled = YES;
    } else if (indexPath.section == 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"burdenCell" forIndexPath:indexPath];
        cell.burdenNameLabel.text = [[self.burdens safeObjectAtIndex:indexPath.item] safeObjectForKey:@"name"];
        cell.burdenQualityLabel.text = [[self.burdens safeObjectAtIndex:indexPath.item] safeObjectForKey:@"quality"];
    } else if (indexPath.section == 2){
        cell = [tableView dequeueReusableCellWithIdentifier:@"stepCell" forIndexPath:indexPath];
        
        if (indexPath.row == self.steps.count - 1) {
            cell.stepNextImgView.hidden = YES;
        }else {
            cell.stepNextImgView.hidden = NO;
        }
        cell.stepImgView.layer.shadowColor = [UIColor lightGrayColor].CGColor;
        cell.stepImgView.layer.shadowOffset = CGSizeMake(0, 3);
        cell.stepImgView.layer.shadowRadius = 3;
        cell.stepImgView.layer.shadowOpacity = .7;
        
        cell.stepNameLabel.text = [[self.steps safeObjectAtIndex:indexPath.item] safeObjectForKey:@"step"];
        [cell.stepImgView sd_setImageWithURL:[NSURL URLWithString:[[self.steps safeObjectAtIndex:indexPath.item] safeObjectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            //NSLog(@"步骤中的图片尺寸：%@", NSStringFromCGSize(image.size));
            cell.stepImgAspect.constant = image.size.width/image.size.height;
            [cell layoutSubviews];
        }];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
        
        NSDictionary *item = [self.commentList safeObjectAtIndex:indexPath.row];
        NSString *avatarAddressStr = [item safeObjectForKey:@"avatar"];
#if DEBUG
        avatarAddressStr = [avatarAddressStr stringByReplacingOccurrencesOfString:@"https" withString:@"http"];
#else
#endif
        [cell.commentUserHeadImgView sd_setImageWithURL:[NSURL URLWithString:avatarAddressStr]];
        cell.commentUserNameLabel.text = [item safeObjectForKey:@"name"];
        cell.commentContentLabel.text = [item safeObjectForKey:@"content"];
        cell.commentTimeLabel.text = [item safeObjectForKey:@"time"];
        if ([[User userID] isEqualToString:[NSString stringWithFormat:@"%@",[item safeObjectForKey:@"u_id"]]]) {
            cell.commentDeleteButton.hidden = NO;
        }else {
            cell.commentDeleteButton.hidden = YES;
        }
        cell.deleteCommentContent = ^{
            [self deleteCommentContentByListID:[item safeObjectForKey:@"id"]];
        };
        return cell;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    }else {
        return 44.0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    }else {
        DetailGroupHeaderView *headerView = [[DetailGroupHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
        if (section == 1) {
            headerView.groupNameLabel.text = @"食材";
        }
        if (section == 2){
            headerView.groupNameLabel.text = @"做法";
        }
        if (section == 3){
            headerView.groupNameLabel.text = @"评论区";
        }
        headerView.groupNameLabel.font = [UIFont fontWithName:@"AppleSDGothicNeo-Bold" size:20.0];
        
        return headerView;
    }
}
#pragma mark - scrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.commentView.textView resignFirstResponder];
}
#pragma mark - AVSpeechSynthesizerDelegate
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance {
    [_speechButton setImage:[[UIImage imageNamed:@"speaking"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance *)utterance {
    [_speechButton setImage:[[UIImage imageNamed:@"speechImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance *)utterance {
    [_speechButton setImage:[[UIImage imageNamed:@"speaking"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(nonnull AVSpeechUtterance *)utterance {
    [_speechButton setImage:[[UIImage imageNamed:@"speechImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
}

#pragma mark - notification
- (void)keyboardChange:(NSNotification *)sender {
    CGRect frame = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = frame.size.height;
    
    __weak typeof(self) ws = self;
    if ([sender.name isEqualToString:UIKeyboardWillShowNotification]) {
        [_commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(ws.view.mas_bottom).offset(-height);
        }];
    }else if ([sender.name isEqualToString:UIKeyboardWillHideNotification]){
        [_commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(ws.view.mas_bottom);
        }];
    }
}
#pragma mark - public
+ (instancetype)detailVCFromStroyBoard {
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"detailVC"];
}
#pragma mark - private
- (NSArray *)componentBurden:(NSString *)burden {
    NSMutableArray *result = [@[] mutableCopy];
    NSArray *colonArray = [burden componentsSeparatedByString:@";"];
    for (NSString *item in colonArray) {
        NSArray *commaArray = [item componentsSeparatedByString:@","];
        NSMutableDictionary *burdenDict = [@{} mutableCopy];
        [burdenDict setSafeValue:[commaArray safeObjectAtIndex:0] forKey:@"name"];
        [burdenDict setSafeValue:[commaArray safeObjectAtIndex:1] forKey:@"quality"];
        [result addObject:burdenDict];
    }
    return result;
}
- (void)interactiveWithType:(INTERACTIVETYPE)interactiveType {
    NSMutableDictionary *params = [@{} mutableCopy];
    [params setSafeValue:[self.foodInfo safeObjectForKey:@"id"] forKey:@"cid"];
    [params setSafeValue:[User userID] forKey:@"uid"];
    [params setSafeValue:[self.foodInfo safeObjectForKey:@"title"] forKey:@"title"];
    [params setSafeValue:[self.foodInfo safeObjectForKey:@"imtro"] forKey:@"imtro"];
    [params setSafeValue:[[self.foodInfo safeObjectForKey:@"albums"] safeObjectAtIndex:0] forKey:@"albums"];
    [params setSafeValue:@(interactiveType) forKey:@"type"];
    
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/collection_browse" params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"code"] isEqual:@1]) {
            if (interactiveType == INTERACTIVETYPE_COLLECT) {
                if (!isCollect) {
                    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:0 animations:^{
                        [self.collectItem setImage:[[UIImage imageNamed:@"food_collect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
                    } completion:nil];
                }else {
                    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:0 animations:^{
                        [self.collectItem setImage:[[UIImage imageNamed:@"food_notCollect"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
                    } completion:nil];
                }
                isCollect = !isCollect;
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"浏览/收藏failure: %@",error);
    }];
}
- (void)collectThisFood {
    if (![User isLogin]) {
        LoginViewController *loginVC = [LoginViewController loginVCFromStoryBoard];
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    [self interactiveWithType:INTERACTIVETYPE_COLLECT];
}
- (void)shareThisFood {
    if (![User isLogin]) {
        LoginViewController *loginVC = [LoginViewController loginVCFromStoryBoard];
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession), @(UMSocialPlatformType_WechatTimeLine)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        NSMutableDictionary *shareInfo = [@{} mutableCopy];
        [shareInfo setSafeValue:[self.foodInfo safeObjectForKey:@"albums"][0] forKey:shareThumbImgStr];
        [shareInfo setSafeValue:[self.foodInfo safeObjectForKey:@"title"] forKey:shareTitle];
        [shareInfo setSafeValue:[self.foodInfo safeObjectForKey:@"imtro"] forKey:shareDescr];
        [shareInfo setSafeValue:[self.foodInfo safeObjectForKey:@"shareUrl"] forKey:shareWebPageURL];
        
        [ShareManager shareWebPageToPlatformType:platformType shareInfo:shareInfo success:^{
        } failure:^(NSString * _Nonnull msg) {
        }];
    }];
}
- (void)updateCommentViewFrameByCommentTextSize:(CGSize)textSize object:(DetailViewController *)obj {
    if (textSize.height > 88) {
        [obj.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@88);
        }];
    }else if (textSize.height > 44) {
        [obj.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(textSize.height + 10));
        }];
    }else {
        [obj.commentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@44);
        }];
    }
    __weak typeof(obj) subObj = obj;
    [obj.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(subObj.view.mas_bottom).offset(-subObj.commentView.bounds.size.height);
    }];
}
- (void)sendCommentContent:(NSString *)content {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/comment" params:@{@"cid":@(self.foodID),
                                                                                          @"uid":[User userID],
                                                                                          @"content":content
                                                                                          } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                                              [SVProgressHUD showSuccessWithStatus:@"评论成功!"];
                                                                                              self.commentView.textView.text = nil;
                                                                                              [self.commentView.textView resignFirstResponder];
                                                                                              [self fetchCommentList];
                                                                                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                                              
                                                                                          }];
}
- (void)fetchCommentList {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/comment_list" params:@{@"cid":@(self.foodID)} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject valueForKey:@"show_data"] isKindOfClass:[NSArray class]]) {
            self.commentList = [NSArray arrayWithArray:[responseObject safeObjectForKey:@"show_data"]];
        }else {
            self.commentList = nil;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)speechSteps {
    if ([_synth isPaused]) {
        [_synth continueSpeaking];
    }else {
        [_synth pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
    if (!_synth || ![_synth isSpeaking]) {
        NSMutableString *speechStr = [@"具体步骤如下：\n" mutableCopy];
        for (int i = 1; i <= self.steps.count; i++) {
            NSString *stepDescription = [[self.steps safeObjectAtIndex:i-1] safeObjectForKey:@"step"];
            NSString *occurrenceStr = [NSString stringWithFormat:@"%d.", i];
            [speechStr appendFormat:@"第%d步 \n %@ \n", i, [stepDescription stringByReplacingOccurrencesOfString:occurrenceStr withString:@""]];
        }
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:speechStr];
        utterance.pitchMultiplier = 0.8;
        utterance.rate = 0.38;
        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithIdentifier:@"com.apple.ttsbundle.siri_male_zh-CN_compact"];
        utterance.voice = voice;
        _synth = [[AVSpeechSynthesizer alloc] init];
        _synth.delegate = self;
        [_synth speakUtterance:utterance];
    }
}
- (void)deleteCommentContentByListID:(NSString *)commentID {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/del_comment" params:@{@"uid":[User userID],
                                                                                              @"id":commentID
                                                                                              } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                                                  [self fetchCommentList];
                                                                                              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                                              }];
    
    [self fetchCommentList];
}
#pragma mark - setter
- (void)setFoodInfo:(NSDictionary *)foodInfo {
    _foodInfo = foodInfo;
    if (!self.steps) {
        self.steps = [foodInfo safeObjectForKey:@"steps"];
    }
    if (!self.burdens) {
        self.burdens = [self componentBurden:[NSString stringWithFormat:@"%@;%@",[foodInfo safeObjectForKey:@"ingredients"],[foodInfo safeObjectForKey:@"burden"]]];
    }
    if (!self.img_stepsURL) {
        self.img_stepsURL = [foodInfo safeObjectForKey:@"img_steps"];
    }
}
#pragma mark - getter
- (CommentView *)commentView {
    if (!_commentView) {
        _commentView = [[CommentView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        [self.view addSubview:_commentView];
        __weak typeof(self) ws = self;
        _commentView.sendCommentContent = ^(NSString * _Nonnull content) {
            if (content.length == 0) {
                [SVProgressHUD showErrorWithStatus:@"评论内容不能为空!"];
                return ;
            }
            [ws sendCommentContent:content];
        };
    }
    return _commentView;
}
- (UIButton *)speechButton {
    if (!_speechButton) {
        _speechButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:_speechButton];
        [_speechButton setImage:[[UIImage imageNamed:@"speechImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_speechButton addTarget:self action:@selector(speechSteps) forControlEvents:UIControlEventTouchUpInside];
        _speechButton.layer.shadowOffset = CGSizeMake(3, 3);
        _speechButton.layer.shadowRadius = 3;
        _speechButton.layer.shadowOpacity = 0.7;
        _speechButton.layer.shadowColor = [UIColor blackColor].CGColor;
        //创建动画
        CAKeyframeAnimation *keyAnimaion = [CAKeyframeAnimation animation];
        keyAnimaion.keyPath = @"transform.rotation";
        keyAnimaion.values = @[@(-10 / 180.0 * M_PI),@(10 /180.0 * M_PI),@(-10/ 180.0 * M_PI)];
        keyAnimaion.removedOnCompletion = NO;
        keyAnimaion.fillMode = kCAFillModeForwards;
        keyAnimaion.duration = 0.3;
        keyAnimaion.repeatCount = MAXFLOAT;
        [_speechButton.layer addAnimation:keyAnimaion forKey:nil];
    }
    return _speechButton;
}
@end
